<template>
  <div class="product">
    <!-- 搜索框 -->
    <div class="search">
      <!-- 
            multiple 多条搜索
            filterable 是否可搜索
            remote 是否为远程搜索
            reserve-keyword 多选且可搜索时，是否在选中一个选项后保留当前的搜索关键词
            remote-method 远程搜索方法
            clearable 后面加上 x 号
         -->
      <template>
        <el-select
          v-model="searchValue"
          filterable
          clearable
          remote
          @blur="searchBlur"
          @change="searchTextChange"
          @clear="clear"
          reserve-keyword
          placeholder="请输入姓名 如果不更新,点击右侧搜索按钮"
          :remote-method="remoteMethod"
          :loading="loading"
        >
          <el-option
            v-for="item in searchList"
            :key="item.sId"
            :label="item.name"
            :value="item.name"
          >
          </el-option>
        </el-select>
      </template>
      <!-- 搜索按钮 -->
      <el-button
        type="primary"
        @click="onSearchButtonClick"
        class="btn"
        icon="el-icon-search"
        plain
      ></el-button>
      <!-- 添加按钮 -->
      <el-button type="primary" v-has="'add'" @click="addStu"
        >添加项目</el-button
      >
    </div>
    <!-- 班级选择 -->
    <div class="class">
      <template>
        选择班级:
        <el-select
          v-model="cls"
          @visible-change="classVisible"
          @change="classChange"
          filterable
          placeholder="请选择班级"
        >
          <el-option label="全部" value="all"></el-option>
          <el-option
            v-for="(item, index) in classOptions"
            :key="index"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
      </template>
    </div>
    <!-- 导出excel表格 -->
    <div class="excel">
      <el-button type="primary" @click="exportExcel">导出excel表格</el-button>
    </div>
    <!-- 表格 -->
    <div class="productTable">
      <el-table :data="stuData" v-loading="loading" border style="width: 100%">
        <el-table-column
          prop="headimgurl"
          label="头像"
          align="center"
          width="120"
        >
          <template slot-scope="scope">
            <el-avatar
              shape="square"
              :size="50"
              fit="fill"
              :src="scope.row.headimgurl"
            ></el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="姓名" align="center" width="200">
        </el-table-column>
        <el-table-column prop="class" align="center" label="班级" width="240">
        </el-table-column>
        <el-table-column
          prop="productUrl"
          align="center"
          label="项目"
          width="240"
        >
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="{ row }">
            <el-button
              type="primary"
              round
              icon="el-icon-edit"
              v-has="'read'"
              @click="chakan(row)"
              >查看</el-button
            >
            <el-button
              type="primary"
              @click="editStu(row)"
              v-has="'edit'"
              icon="el-icon-edit"
              round
              >编辑</el-button
            >
            <el-button
              type="danger"
              @click="deleteStu(row)"
              round
              v-has="'delete'"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- dialog弹出框 -->
    <qf-dialog></qf-dialog>

    <!-- 分页器 -->
    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next"
        @current-change="changePage"
        :page-size="dataCount"
        :total="total"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import dialog from "@/components/dialog";
import {
  getStuList,
  searchStu,
  addStuReq,
  editStuReq,
  deleteStu as deleteStuReq,
} from "@/api";
import qfExportExcel from "qf-export-excel";
export default {
  components: {
    "qf-dialog": dialog,
  },
  data() {
    return {
      stuData: [],
      // 添加loading
      loading: true,
      searchValue: "",
      cls: "",
      blurSearchValue: "",
      searchList: [],
      classOptions: [],
      params: {
        class: "",
        count: 5,
      },
      dataPage: "", //页码
      dataCount: 5, //每页展示的数量
      total: 20, //总共数据条数
    };
  },
  created() {
    this.updateStuTable();
  },
  methods: {
    // 分页器
    changePage(page) {
      this.dataPage = page;
      // 点击分页切换的时候 判断是否搜索了 搜索栏 就在搜索结果中进入后面的页码
      this.getStu(this.params);
    },
    getStu(params) {
      this.loading = true;
      params = this.params;
      params.count = this.dataCount;
      params.page = this.dataPage;
      this.updateStuTable();
      getStuList(params).then((res) => {
        if (res.data.state) {
          this.stuData = res.data.data;
          this.total = res.data.total;
          this.loading = false;
        } else {
          this.$message.console.warn(ing("获取数据失败"));
          this.loading = false;
        }
      });
    },
    // 导出Excel
    exportExcel() {
      let titlelist = [
        { title: "头像地址", key: "headimgurl" },
        { title: "项目", key: "productUrl" },
        { title: "班级", key: "class" },
        { title: "姓名", key: "name" },
      ];
      let dataSource = this.stuData; //表格数据数组
      qfExportExcel(titlelist, dataSource, "学员数据");
    },
    addStuRequest(params) {
      // 用于dialog点击确定后 增加学员的请求 将来通过dialog的eventBus进行调用
      addStuReq(params).then((res) => {
        console.log(res.data);
        if (res.data.state) {
          // 添加成功 更新列表
          this.updateStuTable();
        }
      });
    },
    editStuRequest(params) {
      // 用于dialog点击确定后 编辑学员的请求 将来通过dialog的eventBus进行调用
      editStuReq(params).then((res) => {
        console.log(res.data);
        if (res.data.state) {
          // 更新成功 更新列表
          this.updateStuTable();
        }
      });
    },
    // 删除学员
    deleteStu(row) {
      // elementui 二次确认
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let sId = row.sId;
          deleteStuReq(sId).then((res) => {
            // console.log(res.data);
            if (res.data.state) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });

              this.updateStuTable();
            } else {
              this.$message.error("删除出错");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 查看学员
    chakan(row) {
      console.log("45645646", row);
      this.$router.push({ path: "profill", query: { id: row.sId } });
      // this.$router.push(`/StudentManager/profill?${row.sId}`)
    },
    // 编辑学员
    editStu(row) {
      console.log("123456", row);
      let row1 = { ...row }; //引用数据类型 能影响接下来操作 所以 要先用一下浅拷贝
      this.$bus.$emit("editStu", row1);
    },
    // 弹出dialog
    addStu(row) {
      this.$bus.$emit("addStu");
    },
    //   更新表格数据
    updateStuTable(params = { count: 5, page: 1, classes: "" }) {
      // 发送请求 获取学员数据
      this.loading = true;
      getStuList(params).then((res) => {
        // 获取数据成功
        this.stuData = res.data.data;
        // 关闭loading
        this.loading = false;
      });
    },
    classVisible(isVisible) {
      // 班级选择框展开/收起触发的事件
      // 展开的时候需要获取所有数据 调用获取列表的方法
      console.log(isVisible);
      if (isVisible) {
        //展开
        getStuList().then((res) => {
          // 需要去重操作
          console.log(res.data.data);
          let norepeatArr = [];
          res.data.data.forEach((item) => {
            norepeatArr.push(item.class);
            norepeatArr = Array.from(new Set(norepeatArr));
          });
          console.log("===去重", norepeatArr);
          this.classOptions = norepeatArr;
        });
      }
    },
    classChange(query) {
      // console.log('111',query);
      // 如果query是all 代表要显示所有说句 后台的设定是 class字段传空字符串就返回所有班级的数据 所以一下用一个三元表达式
      let classes = query === "all" ? "" : query;
      // 选择班级
      this.updateStuTable({ page: 1, count: 10, classes });
    },
    searchTextChange(searchText) {
      // 搜索框选中值发生变化的事件
      // console.log(searchText);
      console.log(this.searchList);
      this.stuData = this.searchList;
    },
    onSearchButtonClick() {
      // 点击搜索按钮 触发更新
      this.remoteMethod(this.blurSearchValue);
      this.searchTextChange();
    },
    searchBlur() {
      // 搜索框失去焦点 保持输入框的内容
      // 将储存好的输入框的值 设置给select组件
      this.searchValue = this.blurSearchValue;
    },
    clear() {
      // 清空输入框的时候 会显示所有的数据
      this.updateStuTable();
    },
    remoteMethod(query) {
      // 键盘弹起时获取输入值 赋值三方变量 进行输入框内存储
      this.blurSearchValue = query;
      console.log("搜索框输入", query);
      // 发送请求 搜索学员
      let key = query;
      let page = 1;
      let count = "";
      searchStu(page, count, key).then((res) => {
        console.log("发送搜索学员接口", res);
        this.searchList = res.data.data;
      });
    },
  },
  mounted() {
    //页面加载 获取表格数据
    this.$bus.$on("adding", (params) => {
      this.addStuRequest(params);
    });
    this.$bus.$on("adding", (params) => {
      this.editStuRequest(params);
    });
  },
};
</script>

<style scoped>
.search {
  line-height: 60px;
  text-align: left;
  margin: 20px 0;
}
.search .btn {
  margin-left: 3px;
}
.class {
  line-height: 60px;
  text-align: left;
  margin: 20px 0;
}
.el-table__row {
  line-height: 40px;
}
</style>
